import win32api
import win32con
import win32com.client
import win32com
import os
file_path = "./AutoWifi.exe"
key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
key_name = 'AutoConnectSchoolWifi'

def setAutoStartup():
    # 获取当前用户的startup 文件夹路径
    startup_folder = os.path.join(os.environ['USERPROFILE'],'AppData','Roaming','Microsoft','Windows','Start Menu','Programs','Startup')
    target_path = os.path.abspath(file_path)
    shortcut_path = os.path.join(startup_folder,os.path.splitext(os.path.basename(file_path))[0]+".lnk")
    shell = win32com.client.Dispatch("WScript.shell")
    shortcut = shell.CreateShortCut(shortcut_path)
    shortcut.Targetpath = target_path
    shortcut.WorkingDirectory = os.path.dirname(shortcut_path)
    shortcut.save()
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, key_path, 0, win32con.KEY_ALL_ACCESS)
    win32api.RegSetValueEx(key, key_name, 0, win32con.REG_SZ, shortcut_path)
    win32api.RegCloseKey(key)
    # print('已设置开机自启动')


# 取消开机自启动
def cancelAutoStartup():
    # 删除快捷方式
    startup_folder = os.path.join(
        os.environ['USERPROFILE'], 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')
    shortcut_path = os.path.join(startup_folder, os.path.splitext(os.path.basename(file_path))[0] + '.lnk')
    os.remove(shortcut_path)
    # 删除注册表项
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, key_path, 0, win32con.KEY_ALL_ACCESS)
    win32api.RegDeleteValue(key, key_name)
    win32api.RegCloseKey(key)
    # print('已取消开机自启动')
